from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from goods.models import *
import jwt
from django.conf import settings
from .xiaodada import Dada,Wang
import redis
from django.core.paginator import Paginator
# Create your views here.

class CarouselAPPView(APIView):
    def get(self,request):
        # 查询轮播图数据

        carousels = Carousel.objects.all()

        # 组织json数据结构
        temp = []
        for carousel in carousels:
            # 获取一个轮播图对象并组织成字典
            temp_dict = {
                'id':carousel.id,
                'imgOath':carousel.imgPath,
                'describes':carousel.describes
            }
            # 字典数据追加列表
            temp.append(temp_dict)

        # 返回响应
        return Response({
            'code':200,
            'msg':'加载轮播图成功',
            'data':temp,
        })

# 组织json结构的函数
def org_json(que):
    temp = []
    for i in que:
        temp_dict = {
            'id' : i.id,
            'sku_name':i.sku_name,
            'price' :i.price,
            'selling_price':i.selling_price,
            'img':i.img,
            'title':i.title,
            'instruction':i.instruction,
            'count':i.count,
            'stock':i.stock,
            'cate':i.cate.id,
            'online':i.online,
        }
        temp.append(temp_dict)
    return temp



# 一类商品
class OneCategoryAPIView(APIView):
    def get(self,request):
        # 接受前端数据
        # query_params   query  query  query  query  query query params query_params
        cate_name = request.query_params.get('categoryName')
        print('接受前端的类别',cate_name)

        # 根据类别名查询类别对象  .first()
        cat__obj = Category.objects.filter(cate_name=cate_name).first()

        if not cate_name:
            return Response({
                'code':400,
                'msg':'查询的类别不存在'
            })

        # 根据类别对象，查询该类的所有商品

        goods = cat__obj.goods_set.all()

        # 组织商品数据的json结构

        data = org_json(goods)

        return Response({
            'code':200,
            'msg':'加载%r类别商品成功'%cate_name,
            'data':data
        })

# def org_json(queryset):
#     """
#     # 组织json数据结构的函数
#     :param queryset:查询集
#     :return: 字典列表
#     """
#     temp = []
#     for i in queryset:
#         temp_dict = {
#             'id': i.id,
#             'sku_name': i.sku_name,
#             'price': i.price,
#             'selling_price': i.selling_price,
#             'img': i.img,
#             'title': i.title,
#             'instruction': i.instruction,
#             'count': i.count,
#             'stock': i.stock,
#             'cate': i.cate.id,
#             'online': i.online
#         }
#
#         temp.append(temp_dict)
#     return temp
#
#
# class OneCategoryAPIView(APIView):
#     def get(self, request):
#         cate_name = request.query_params.get('categoryName')
#         print('接收前端的数据', cate_name)
#         # 根据类别名称查询类别对象
#         cate_obj = Category.objects.filter(cate_name=cate_name).first()
#         if not cate_obj:
#             return Response({
#                 'code': 400,
#                 'msg': '查询的类别不存在'
#             })
#         # 根据类别对象，查询该类的所有商品
#         goods = cate_obj.goods_set.all()
#
#         # 组织商品数据的json结构 ---序列化
#         data = org_json(goods)
#         return Response({
#             'code':200,
#             'msg':'加载%r类别商品成功'%cate_name,
#             'data':data
#         })

# 热门商品
class HotProduct(APIView):
    def get(self,request):
        # 接受前端参数
        cate_name_list = request.query_params.getlist('categoryName[]')
        print('python自行',request.query_params)
        print('是否接受的到',cate_name_list)

        # 根据类别名称查询类别对象
        cate_objs = [Category.objects.filter(cate_name=cate_name).first() for cate_name in cate_name_list]

        # 根据类别对象查询商品数据
        goods = [cate_obj.goods_set.all() for cate_obj in cate_objs if cate_obj]

        from functools import reduce
        # 将所有的查询集合并
        r = reduce(lambda x, y:x|y, goods).order_by("-count")
        print('合并的查询集',r)

        # 组织商品的json数据结构

        goods_ser = org_json(r)

        return Response({
            'code': 200,
            'msg': '加载%r类别商品成功',
            'data': goods_ser
        })

# 商品详情的视图
class GoodDetai(APIView):
    def get(self,request):
        # 获取前端id
        good_id = request.query_params.get('productID')
        print('xiaodada',good_id)

        # 根据商品id查询商品对象
        good_obj = Goods.objects.filter(id=good_id).first()

        if not good_obj:
            return Response({
                'code':400,
                'msg':'当前商品不存在'
            })

        # 组织响应数据
        data = org_json([good_obj])[0]

        return Response({
            'code':200,
            'msg':'加载商品成功',
            'data':data
        })


# 商品详情轮播图
class GoodImgs(APIView):
    def get(self,request):
        # 接受前端参数
        goods_id = request.query_params.get('productID')

        # 根据商品id查询商品图片直接查询图片数据
        images = GoodImg.objects.filter(good_id=goods_id)

        # json数据序列化
        temp = []
        for i in images:
            temp_dict = {
                'id':i.id,
                'img':i.img,
                'title':i.title,
            }
            temp.append(temp_dict)

        return Response({
            'code':200,
            'msg':'返回成功',
            'data':temp
        })

# 添加历史记录

class Histoy(APIView):
    def post(self,request):
        # 获取前端数据

        good_id = request.data.get('productID')
        token = request.headers.get('Authorization')

        print('查看参数',good_id,'小达达',token)

        # 判断token是否存在
        if not token:
            return Response({
                'code':400,
                'msg':'用户没有登入，请登入'
            })

        # token解码
        try:
            payload = jwt.decode(token,key=settings.SECRET_KEY,algorithms=['HS256'])
            print('解码信息',payload)
        except Exception as s:
            print('解码错误',s)
            return Response({
                'code':400,
                'msg':'无效的token或者已过期'

            })
        # 获取用户信息，并添加历史记录
        print('小达达最帅',payload)
        uid = payload.get('uid')

        key = 'histoey_%s'%uid

        redis_conn = redis.Redis(host='localhost',port=6379,password='123321')

        # 添加历史记录
        redis_conn.lrem(key,0,good_id)
        redis_conn.lpush(key,good_id)
        redis_conn.ltrim(key,0,4)

        redis_conn.close()

        return Response({
            "code": 200,
            'msg': '添加历史记录成功！'
        })






# 加载所有类别的商品

class AllCategoods(APIView):
    def get(self,request):
        # 查询所有类别对象
        cate_queryset = Category.objects.all()

        # 组织数据结构


        temp = []
        for i in cate_queryset:
            temp_dada = {
                'id':i.id,
                'cate_name':i.cate_name,

            }
            temp.append(temp_dada)

        # 返回响应
        return Response({
            'code':200,
            'msg':'加载商品成功',
            'category':temp
        })


# 加载所有商品的视图

class Goodsall(APIView):
    def post(self,request):
        # 获取前端数据
        categoryID = request.query_params.get('categoryID')
        currentPage = request.data.get('currentPage')
        pageSize = request.data.get('pageSize')

        print('所有商品接受的前端数据',categoryID,currentPage,pageSize)

        # 加载所有商品


        goods_queryset = Goods.objects.all()



        # 分页数据
        paginator = Paginator(goods_queryset,pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list

        # 组织josn数据
        goods_list = org_json(data)


        # 返回响应
        return Response({
            'code':200,
            'msg':'商品接受成功',
            'product':goods_list,
            'total':goods_queryset.count()
        })


# 单个商品显示
class Goodsget(APIView):
    def post(self,request):
        # 接受前端数据
        categoryID = request.data.get('categoryID')[0]
        currentPage = request.data.get('currentPage')
        pageSize = request.data.get('pageSize')

        print('所有商品接受的前端数据', categoryID)

        # 获取当前id
        category = Category.objects.filter(id=categoryID).first()



        # 反向查询
        wang = category.goods_set.all()

        # 分页数据
        paginator = Paginator(wang, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list


        dada = org_json(data)

        return Response({
            'code':200,
            'msg':'分类商品加载成功',
            'product':dada,
            'total':wang.count()
        })











